package org.eva.cynosure.config;

import org.eva.cynosure.service.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    UserDetailsService customUserService() {
        return new CustomUserService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();//关闭csrf

        http.authorizeRequests()//通过authorizeRequests方法来开始请求权限配置
            .antMatchers("/admin/**").hasRole("ADMIN")//请求匹配/admin/**，只有拥有ROLE_ADMIN角色的用户可以访问
            .antMatchers("/user/**").hasAnyRole("ADMIN","USER") //请求匹配/user/**，拥有ROLE_ADMIN或ROLE_USER角色的用户都可以访问
            .anyRequest().authenticated(); //其余所有的请求都需要认证后(登录后)才可以访问。

        http.formLogin()//通过formLogin方法定制登录操作
            .loginPage("/login")//定制登录页面的访问地址
            .failureUrl("/login?error")//登录失败后转向的页面
            .permitAll()
            .and()
            .logout()//定制注销行为
            .logoutUrl("/logout")//指定注销的URL路径
            .logoutSuccessUrl("/login?logout")//注销成功后转向的页面
            .permitAll();
    }
}
